<template>
  <div class="content-wraper">
    <div class="search-box">
      <el-form label-width="100px" :inline="true">
        <el-form-item label="项目名称">
          <el-input v-model="selectedProject.projName" readonly @click.native="showProjectModal = true">
            <i slot="suffix" class="el-input__icon el-icon-circle-plus-outline" />
          </el-input>
        </el-form-item>
        <el-button type="success" icon="el-icon-upload2" :loading="uploading" @click="importFile()">导入</el-button>
        <!-- <el-button type="warning" @click="reset()">重置</el-button> -->
        <el-button type="warning" icon="el-icon-download" @click="downloadFile()">模板下载</el-button>
        <el-button type="primary" :loading="saveLoading" style="float: right;" @click="save()">保存</el-button>
        <el-tag type="success" style="float: right; margin-top: 5px;">
          <span>合计:</span><span>{{ displaySumAmount }}</span>
        </el-tag>
        <input ref="uploadELe" type="file" style="display: none;" @change="fileChange($event)">
      </el-form>
    </div>
    <div class="detail">
      <com-table
        ref="tableChecklist"
        v-model="selectRow"
        highlight-current-row
        default-expand-all
        :data="dataList"
        :columns="columns"
        row-key="number"
        :no-page="true"
        :tree-props="{children: 'childrens', hasChildren: 'hasChildren'}"
      >
        <template v-slot:contractWorkVolume="{row}">
          <el-input v-model="row.contractWorkVolume" />
        </template>
        <template v-slot:price="{row}">
          <el-input v-model="row.price" />
        </template>
        <template v-slot:amount="{row}">
          <el-input v-model="row.amount" />
        </template>
        <template v-slot:drawingWorkVolume="{row}">
          <el-input v-model="row.drawingWorkVolume" />
        </template>
        <template v-slot:measuredWorkVolume="{row}">
          <el-input v-model="row.measuredWorkVolume" />
        </template>
        <template v-slot:remark="{row}">
          <el-input v-model="row.remark" />
        </template>
      </com-table>
    </div>
    <projectSelect :show-modal.sync="showProjectModal" @getSelectedData="getSelectedData" />
  </div>
</template>

<script>
import { getProjectChecklistList, deleteProjectInfo, importProjectChecklist, addProjectChecklist } from '@/api/contractManage'
// import moment from 'moment'
import { saveAs } from 'file-saver'
// const modelFile = require('@/assets/工程量清单导入模板.xls')
import { getDictName } from '@/utils/comm'
// import addProjectInfo from '../generalContract/addProjectInfo.vue'
import projectSelect from './projectSelectModal'
import { projectInfoProjStatus, projectInfoProjType, projectInfoProjMode } from '@/utils/dicData'
export default {
  name: 'GeneralContractList',
  components: {
    projectSelect
  },
  data() {
    return {
      checked: false,
      imported: false,
      showProjectModal: false,
      selectedProject: {
        projName: ''
      },
      selectRow: null,
      uploading: false,
      saveLoading: false,
      getDictName,
      projectInfoProjStatus,
      projectInfoProjType,
      projectInfoProjMode,
      dataList: [],
      displaySumAmount: 0,
      total: 0,
      pageParams: {
        pageNum: 1,
        pageSize: 10
      },
      showModal: false,
      optType: 'add',
      unitDetail: {},
      columns: [
        {
          label: '清单编号',
          prop: 'number'
        },
        {
          label: '清单名称',
          prop: 'name'
        },
        {
          label: '清单单位',
          prop: 'unit'
        },
        {
          label: '合同工程量',
          prop: 'contractWorkVolume',
          slot: 'contractWorkVolume'
        },
        {
          label: '单价',
          prop: 'price',
          slot: 'price'
        },
        {
          label: '金额',
          prop: 'amount',
          slot: 'amount'
        },
        {
          label: '图纸工程量',
          prop: 'drawingWorkVolume',
          slot: 'drawingWorkVolume'
        },
        {
          label: '实测工程量',
          prop: 'measuredWorkVolume',
          slot: 'measuredWorkVolume'
        },
        {
          label: '备注',
          prop: 'remark',
          slot: 'remark'
        }
      ]
    }
  },
  computed: {
    disableImport() {
      return this.checked && this.dataList.length > 0 || !this.checked || this.imported
    },
    canSave() {
      return this.imported && this.dataList.length > 0
    }
  },
  mounted() {
    // this.getDataList()
  },
  methods: {
    /**
     * 验证清单编号:
     * 1、清单编号不能为空
     * 2、清单编号不能重复
     */
    validChecklistNumber() {
      // 树结构转为数组结构
      const data = []
      const getMapToArray = (item) => {
        item.forEach(ele => {
          data.push(ele)
          if (ele.childrens) {
            getMapToArray(ele.childrens)
          }
        })
      }
      getMapToArray(this.dataList)

      if (data.find(item => item.number.length === 0)) {
        this.$message.warning('清单编号不能为空！')
        return false
      }

      const source = data.map(item => { return item.number })
      const target = [...new Set(source)]

      if (source.length !== target.length) {
        this.$message.warning('清单编号不能重复！')
        return false
      }

      return true
    },
    // 获取新表格
    getNewTable() {

    },
    importFile() {
      if (!this.selectedProject.id) {
        this.$message.error('请选择项目后再导入')
        return false
      }
      this.$refs.uploadELe.click()
    },
    fileChange(e) {
      const file = e.target.files[0]
      const formData = new FormData()
      formData.append('file', file)
      this.uploadFile(formData)
    },
    uploadFile(data) {
      this.uploading = true
      importProjectChecklist(data).then(res => {
        this.uploading = false
        const { data, msg, code } = res
        if (code === '0001') {
          this.imported = true
          this.dataList = data
          // 获取显示合计金额
          this.getDisplaySumAmount()
        } else {
          this.$message.error(msg || '导入失败')
        }
        this.$refs.uploadELe.value = null
      }).catch(() => {
        this.uploading = false
        this.$refs.uploadELe.value = null
      })
    },
    downloadFile() {
      saveAs(window.location.pathname + '工程量清单导入模板.xls', '工程量清单导入模板.xls')
    },
    getSelectedData(data) {
      this.selectedProject = data
      this.checked = false
      this.getDataList()
    },
    // 获取显示合计金额
    getDisplaySumAmount() {
      let sum = 0
      const formateData = (data) => {
        data.forEach(item => {
          if (item.childrens) {
            formateData(item.childrens)
          }
          if (item.amount) {
            sum += Number.parseFloat(item.amount)
          }
        })
      }
      formateData(this.dataList)
      this.displaySumAmount = sum.toFixed(2)
    },
    getDataList() {
      const params = {
        projectInfoId: this.selectedProject.id
      }
      getProjectChecklistList(params).then(res => {
        this.checked = true
        const { data } = res || {}
        this.dataList = data
        // 获取显示合计金额
        this.getDisplaySumAmount()
      })
    },
    save() {
      const formateData = list => {
        list.map(val => {
          val.projectInfoId = this.selectedProject.id
          if (val.childrens && val.childrens.length > 0) {
            formateData(val.childrens)
          }
        })
        return list
      }
      const validChecklist = this.validChecklistNumber()
      if (!validChecklist) {
        return
      }
      const params = {
        lstProjectChecklistDetail: formateData(this.dataList)
      }
      this.saveLoading = true
      addProjectChecklist(params).then(res => {
        this.saveLoading = false

        const { code, msg } = res || {}
        if (code === '0001') {
          this.$message.success('保存成功')
          this.imported = false
          this.checked = false
          this.getDataList()
        } else {
          this.$message.error(msg || '保存失败')
        }
      }).catch(() => {
        this.saveloading = false
      })
    },
    addProjectInfo() {
      this.optType = 'add'
      this.showModal = true
    },
    editProjectInfo(data) {
      this.optType = 'edit'
      this.unitDetail = data
      this.showModal = true
    },
    viewDetail(data) {
      this.optType = 'detail'
      this.unitDetail = data
      this.showAddFileModal = true
    },
    delProjectInfo(data) {
      this.$confirm('确定要删除该项目基本信息吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const { id } = data
        deleteProjectInfo({
          projectInfoId: id
        }).then(res => {
          const { code, msg } = res
          if (code === '0001') {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getDataList()
          } else {
            this.$message({
              type: 'error',
              message: msg || '删除失败!'
            })
          }
        })
      }).catch(() => {
      })
    },
    search() {
      this.pageParams.pageNum = 1
      this.getDataList()
    },
    reset() {

    }

  }
}
</script>

<style lang="scss" scoped>
.search-box {
  height: 50px;
}
.detail{
  height: calc(100% - 50px);
}
</style>
